package pay.util;

import Dto.orderEntity;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import config.payConfig;
import util.DBUtil;

public class payService {
    public static String order_number;
    public static String shop_name;
    public static double Money;
    private static final String FORMAT = "JSON";

    public static void userPay(String orderNumber, String shopName, double money,
                        HttpServletResponse resp) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getServerUrl(), payConfig.getAppId(),
                payConfig.getPrivateKey(), FORMAT, payConfig.getCharset(), payConfig.getAlipayPublicKey(), payConfig.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl("http://gu9za9.natappfree.cc/notify");
        request.setReturnUrl("http://gu9za9.natappfree.cc/index.jsp");
        order_number = orderNumber;
        shop_name = shopName;
        Money = money;
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNumber);   //订单号
        bizContent.put("total_amount", money); // 订单的总金额
        bizContent.put("subject", shopName);   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        resp.setContentType("text/html;charset=" + payConfig.getCharset());
        resp.getWriter().write(form);
        resp.getWriter().flush();
        resp.getWriter().close();
    }


    public static String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, payConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            if (checkSignature) {
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                HttpSession session1 = request.getSession();
                int user_id = (int) session1.getAttribute("suerId");
                int status =1;

                int res = setPayHistory(user_id, order_number,shop_name, Money, status);
                if(res>0){
                    return "success";
                }
            }
        }
        return "success";
    }

    /**
     * 插入订单到数据库
     */
    public static int setPayHistory(int userId, String order_id,String shopName, double orderMoney,int Status) throws Exception {
        do {
            // 生成新的订单号
            order_id = generateOrderId(userId);
        } while (findIsHasSameOrderId(order_id) > 0); // 如果订单号已存在，重新生成


        // 插入订单到数据库
        int rows = 0;
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "INSERT INTO alluserpayhistory (user_id, order_id, shop_name, money, status) VALUES (?, ?, ?, ?, ?)";
            try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                stmt.setInt(1, userId);
                stmt.setString(2, order_id);
                stmt.setString(3, shopName);
                stmt.setDouble(4, orderMoney);
                stmt.setString(5, "notPay");
                rows = stmt.executeUpdate(); // 执行插入操作
            }
        } catch (SQLException e) {
            throw new Exception("Failed to create order: " + e.getMessage(), e);
        }
        return rows;
    }

    /**
     * 检查订单号是否存在
     */
    public static int findIsHasSameOrderId(String orderId) {
        int rows = 0;
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT COUNT(order_id) FROM alluserpayhistory WHERE order_id = ?";
            try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                stmt.setString(1, orderId);
                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        rows = rs.getInt(1);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }


    /**
     * 生成订单号
     * 格式：年月日时分秒 + 用户ID后4位 + 4位随机数
     */
    public static String generateOrderId(int userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        
        // 用户ID后4位，不足4位前面补0
        String userIdStr = String.format("%04d", userId % 10000);
        
        // 生成4位随机数
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        
        return timestamp + userIdStr + randomNum;
    }
}
